package com.kvn.test.dubbo;


import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSON;
import com.kvn.test.core.ConfigContext;
import com.kvn.test.core.TestContext;

/**
 * @author wzy on 2017/8/8.
 */
public class DubboCommandExecutor {
    Logger logger = LoggerFactory.getLogger(DubboCommandExecutor.class);

    public Object dubboExecute(DubboCommand command) {

    	// 该实例很重要，里面封装了所有与注册中心及服务提供方连接，请缓存
        ReferenceConfig<GenericService> reference = buildReferenceConfig(command);
        mergeRpcContext(command);

        GenericService genericService = ReferenceConfigCache.getCache().get(reference);// 通用泛化接口。从缓存取
        logger.info("Dubbo调用=>" + command);
        Object result = genericService.$invoke(command.getMethodName(), command.getArgsTypes().toArray(new String[command.getArgsTypes().size()]), command.getArgs().toArray());
        logger.info("Dubbo调用返回结果=>" + JSON.toJSONString(result));
        TestContext.getInstance().set_D((Map<String, Object>) result);
        return result;
    }

    private void mergeRpcContext(DubboCommand command) {
//        RpcContext context = RpcContext.getContext();
//        Map<String,String> attachment = new HashMap<String,String>();
//        if(null!=command.getAttachment()){
//            attachment.putAll(command.getAttachment());
//        }
//        context.setAttachments(attachment);
    }

    private ReferenceConfig<GenericService> buildReferenceConfig(DubboCommand command) {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setGroup(command.getGroup()); // 分组调用
        reference.setInterface(command.getInterfaceName()); // 弱类型接口名
        reference.setVersion(command.getVersion());
        
        reference.setTimeout(60000); // 超时毫秒
//        reference.setAsync(false); // 异步调用
        reference.setGeneric(true); // 声明为泛化接口
        reference.setUrl(command.getUrl());

        ApplicationConfig applicationConfig = new ApplicationConfig(); // 服务治理参数
        applicationConfig.setName(ConfigContext.getDubboConfig("dubbo.application.name"));
        applicationConfig.setOwner(ConfigContext.getDubboConfig("dubbo.application.owner"));
        reference.setApplication(applicationConfig);
        RegistryConfig config = new RegistryConfig(ConfigContext.getDubboConfig("dubbo.registry.address"));
        reference.setRegistry(config);
        return reference;
    }

    public static void main(String[] args) {
		System.out.println(int.class.getName());
	}
}
